package com.guojiaming.shop.controller;

import com.guojiaming.shop.bean.ImageFile;
import com.guojiaming.shop.bean.ResponseBody;
import com.guojiaming.shop.bean.ResponseFactory;
import com.guojiaming.shop.config.MyGlobalConfig;
import com.guojiaming.shop.service.ImageFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author vivo
 */
@RestController
@RequestMapping("image")
public class FileController {
    private Logger logger = LoggerFactory.getLogger(FileController.class);
    @Resource
    private ImageFileService imageFileService;
    @Resource
    private MyGlobalConfig myGlobalConfig;


    @PostMapping("upload")
    public ResponseBody<String> upload(@RequestParam(value = "image") MultipartFile image) {
        if (image.isEmpty()) {
            return ResponseFactory.failed("文件为空,上传失败");
        }
        //获取文件名
        String fileName = image.getOriginalFilename();
        //获取后缀名
        if (fileName == null) {
            return ResponseFactory.failed("文件名称获取失败");
        }
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //设置保存的文件名称
        String saveName = UUID.randomUUID() + suffixName;
        //创建文件对象
        File dest = new File(myGlobalConfig.getImagePath(), saveName);
        if (!dest.getParentFile().exists()) {
            if (dest.getParentFile().mkdirs()) {
                logger.info("创建了保存图片的文件夹");
            } else {
                logger.info("文件夹创建失败");
                return ResponseFactory.failed("保存失败,请联系管理员");
            }
        }
        //把文件保存到本地
        try {
            image.transferTo(dest);
        } catch (IOException e) {
            logger.info("图片保存失败", e);
            return ResponseFactory.failed("保存失败:" + e);
        }
        //保存图片信息到数据库
        ImageFile imageFile = new ImageFile();
        imageFile.setPath(dest.getPath());
        imageFile.setUrl(myGlobalConfig.getBaseUrl() + dest.getName());
        ImageFile save = imageFileService.save(imageFile);
        return ResponseFactory.success(save.getUrl(), "上传成功");
    }
}
